/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManageJFrame;

import ManageBLL.BLLManufacture;
import ManageBLL.BLLProduct;
import ManageDAL.DALProduct;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.SQLException;
import javax.swing.table.TableColumn;
import java.util.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
/**
 *
 * @author Pham
 */
public class JFrameManageProduct extends JFrame{
    JPanel pnbasicProduct;
    JPanel pnSearch;
    JPanel pnTable;
    JPanel pnButton;
    JTextField txtSearchName;
    JComboBox cbManu;
    JScrollPane scrollProductTable;
    JTable tbProduct;
    JButton btnAddnew;
    JButton btnEdit;
    JButton btnDel;
    
    BLLProduct bllPro = new BLLProduct();
    
    
    public JFrameManageProduct()
    {
        initializeComponent();
    }

    //initialize all component of the form
    private void initializeComponent() {
        
        pnbasicProduct = new JPanel();
        pnbasicProduct.setLayout(new BoxLayout(pnbasicProduct, BoxLayout.Y_AXIS));
        add(pnbasicProduct);
        
        //add the components search
        pnSearch = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        pnSearch.setSize(new Dimension(800, 100));
        pnSearch.setBorder(BorderFactory.createEmptyBorder(20, 15, 0, 0));
        JLabel lbSearchwithName = new JLabel("Tìm theo tên");
        lbSearchwithName.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        txtSearchName = new JTextField();
        txtSearchName.setPreferredSize(new Dimension(140, 25));
        
        JLabel lbSearchwithManu = new JLabel("Tìm theo hãng sản xuất");
        lbSearchwithManu.setBorder(BorderFactory.createEmptyBorder(0, 25, 0, 5));
        cbManu = new JComboBox();
        cbManu.setPreferredSize(new Dimension(140, 25));
        //cbManu.addItem("Tất cả các hãng...");
        
        //load data from database to combobox
        BLLManufacture bllManu = new BLLManufacture();
        DefaultComboBoxModel dcbManu = bllManu.getComboboxModelManu();
        dcbManu.addElement("Tất cả các hãng...");
        cbManu.setModel(dcbManu);
        cbManu.setSelectedIndex(cbManu.getItemCount()-1);
        
        
        JButton btnSearch = new JButton("Tìm kiếm");
        ImageIcon iconSearch = new ImageIcon(new ImageIcon(JFrameManageProduct.class.getResource("../Images/find.png"))
                .getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH));
        btnSearch.setIcon(iconSearch);
        
        btnSearch.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                btnSearchactionPerformed(e);
            }
        });
        
        pnSearch.add(lbSearchwithName);
        pnSearch.add(txtSearchName);
        pnSearch.add(lbSearchwithManu);
        pnSearch.add(cbManu);
        pnSearch.add(btnSearch);
        
        
        pnbasicProduct.add(pnSearch, BorderLayout.NORTH);
        JPanel pnViewall = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        pnViewall.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
        JButton btnViewAll = new JButton("Hiển thị tất cả sản phẩm");
        btnViewAll.setPreferredSize(new Dimension(180, 30));
        pnViewall.add(btnViewAll, BorderLayout.WEST);
        pnbasicProduct.add(pnViewall);
        btnViewAll.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                btnViewAllactionPerformed(e);
            }
        });
        
        //load data from database
        pnTable = new JPanel();
        tbProduct = new JTable();
        
        loadDataProduct(bllPro.getDTM());
        scrollProductTable = new JScrollPane(tbProduct);
        scrollProductTable.setPreferredSize(new Dimension(500, 200));
        scrollProductTable.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20));
        //pnTable.add(scrollProductTable, BorderLayout.WEST);
        pnbasicProduct.add(scrollProductTable, BorderLayout.CENTER);
        
        //add button---------------
        pnButton = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        btnAddnew = new JButton("Thêm");
        ImageIcon iconAddnew = new ImageIcon(new ImageIcon(JFrameManageProduct.class.getResource("../Images/netvibes.png"))
                .getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH));
        btnAddnew.setIcon(iconAddnew);
        btnAddnew.setPreferredSize(new Dimension(100, 30));
        btnAddnew.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                btnAddnewactionPerformed(e);
            }

            
        });
        pnButton.add(btnAddnew);
        
        btnEdit = new JButton("Sửa");
        ImageIcon iconEdit = new ImageIcon(new ImageIcon(JFrameManageProduct.class.getResource("../Images/pencil.png"))
                .getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH));
        btnEdit.setIcon(iconEdit);
        btnEdit.setPreferredSize(new Dimension(100, 30));
        btnEdit.setEnabled(false);
        btnEdit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                btnEditactionPerfored(e);
            }
        });
        pnButton.add(btnEdit);
        
        btnDel = new JButton("Xóa");
        ImageIcon iconDel = new ImageIcon(new ImageIcon(JFrameManageProduct.class.getResource("../Images/remove.png"))
                .getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH));
        btnDel.setIcon(iconDel);
        btnDel.setPreferredSize(new Dimension(100, 30));
        btnDel.setEnabled(false);
        btnDel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                btnDelactionPerformed(e);
            }
        });
        pnButton.add(btnDel);
        
        
        pnbasicProduct.add(pnButton);
        
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    //method load data product from database to table
    private void loadDataProduct(DefaultTableModel dtmPro)
    {
        //TableRowSorter
        tbProduct.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                btnEdit.setEnabled(true);
                btnDel.setEnabled(true);
                
            }

            @Override
            public void mousePressed(MouseEvent e) {
                
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                int rowcheck = tbProduct.getSelectedRow();
                if(rowcheck < 0){
                    btnEdit.setEnabled(false);
                    btnDel.setEnabled(false);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
               
            }

            @Override
            public void mouseExited(MouseEvent e) {
                
            }
        });
        tbProduct.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                
            }
        });
        
        tbProduct.setModel(dtmPro);
        tbProduct.setAutoCreateRowSorter(true);
        tbProduct.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tbProduct.getColumnModel().getColumn(0).setPreferredWidth(60);
        tbProduct.getColumnModel().getColumn(1).setPreferredWidth(180);
        tbProduct.getColumnModel().getColumn(2).setPreferredWidth(100);
        tbProduct.getColumnModel().getColumn(3).setPreferredWidth(80);
        tbProduct.getColumnModel().getColumn(4).setPreferredWidth(100);
        tbProduct.getColumnModel().getColumn(5).setPreferredWidth(100);
    }
    
    
    //action method/////////////////////////
    //search action
    private void btnSearchactionPerformed(ActionEvent e) {
        String keyword = txtSearchName.getText().trim();
        String manu = cbManu.getSelectedItem().toString();
//        if(!"".equals(keyword))
//        {
            loadDataProduct(bllPro.getProductbyQuery(keyword, manu));
            //JOptionPane.showMessageDialog(null, manu);
//        }
    }
    
    //view all action
    private void btnViewAllactionPerformed(ActionEvent e)
    {
        loadDataProduct(bllPro.getDTM());
    }
    
    //method action addnew button
    private void btnAddnewactionPerformed(ActionEvent e) {
        try{
            //newDialogPro = new JDialogProduct(this, true);
            JDialogProduct newDialogPro = new JDialogProduct(this, true);
            newDialogPro.addWindowListener(new WindowListener() {

                @Override
                public void windowOpened(WindowEvent e) {
                    
                }

                @Override
                public void windowClosing(WindowEvent e) {
                    //loadDataProduct(bllPro.getDTM());
                }

                @Override
                public void windowClosed(WindowEvent e) {
                        loadDataProduct(bllPro.getDTM());
                                            
                }

                @Override
                public void windowIconified(WindowEvent e) {
                    
                }

                @Override
                public void windowDeiconified(WindowEvent e) {
                    
                }

                @Override
                public void windowActivated(WindowEvent e) {
                    
                }

                @Override
                public void windowDeactivated(WindowEvent e) {
                    
                }
            });
            
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            newDialogPro.setLocation((dim.width - newDialogPro.getWidth())/2, (dim.height - newDialogPro.getHeight())/2);
            newDialogPro.setVisible(true);
        }
        catch(Exception ex){
            System.err.print(ex.getMessage());
        }
    }
    
    //method action Edit button
    private void btnEditactionPerfored(ActionEvent e) {
        int rowcheck = tbProduct.getSelectedRow();
        if(rowcheck > -1 && tbProduct.getSelectedRows().length == 1){
            int ID = (int)tbProduct.getModel().getValueAt(tbProduct.getSelectedRow(), 0);
            JDialogProduct dialogPro = new JDialogProduct(this, true, ID);
            Dimension di = Toolkit.getDefaultToolkit().getScreenSize();
            dialogPro.setLocation((di.width - dialogPro.getWidth())/2, (di.height - dialogPro.getHeight())/2);
            dialogPro.addWindowListener(new WindowListener() {
                @Override
                public void windowClosed(WindowEvent e) {
                        loadDataProduct(bllPro.getDTM());
                                            
                }
                
                @Override
                public void windowOpened(WindowEvent e) {
                    
                }

                @Override
                public void windowClosing(WindowEvent e) {
                    
                }

                @Override
                public void windowIconified(WindowEvent e) {
                    
                }

                @Override
                public void windowDeiconified(WindowEvent e) {
                    
                }

                @Override
                public void windowActivated(WindowEvent e) {
                    
                }

                @Override
                public void windowDeactivated(WindowEvent e) {
                    
                }
            });
            dialogPro.setVisible(true);
        }
        else
            System.out.println("please choose a row");
        
    }
    
    //method action Delete button
    private void btnDelactionPerformed(ActionEvent e) {
        try{
            int rowcheck = tbProduct.getSelectedRow();
            if(rowcheck > -1)
            {
//                int Id = (int)tbProduct.getModel().getValueAt(tbProduct.getSelectedRow(), 0);
    //            int message = JOptionPane.showConfirmDialog(this, "Bạn có chắc muốn xóa", "Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    //            if(message == JOptionPane.YES_OPTION)
    //            {
    //                if(bllPro.delProduct(Id))
    //                JOptionPane.showMessageDialog(this, "Đã xóa");
    //                loadDataProduct(bllPro.getDTM());
    //            }
                DefaultTableModel model = (DefaultTableModel)tbProduct.getModel();
                int[] selectedRows = tbProduct.getSelectedRows();
//                int[] ids = new int[selectedRows.length];
                for(int i = selectedRows.length - 1; i >= 0; i--){
                    int id = (int)tbProduct.getModel().getValueAt(selectedRows[i], 0);
//                    if(bllPro.delProduct(id))
                        model.removeRow(selectedRows[i]);
//                    else
//                        JOptionPane.showMessageDialog(this, "Không thể xóa");
                        System.out.println(id);
                }
                
            }
            else
                JOptionPane.showMessageDialog(this, "Vui lòng chọn sản phẩm muốn xóa");
        }
        catch(Exception ex){
            System.err.printf(ex.getMessage());
        }
    }
    
    //method main of this programe
    public static void main(String[] arg)
    {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrameManageProduct frame = new JFrameManageProduct();
                frame.setPreferredSize(new Dimension(800, 600));
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
